package com.example.backend.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.backend.common.api.R;
import com.example.backend.entity.OperationLog;
import com.example.backend.service.OperationLogService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;


@RestController
@RequestMapping("/admin/log")
@RequiredArgsConstructor
public class LogController {
    
    private final OperationLogService operationLogService;
    
    /**
     * 分页查询操作日志
     */
    @GetMapping
    @PreAuthorize("hasAuthority('system:log:view')")
    public R<IPage<OperationLog>> getLogs(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String module,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) LocalDateTime startTime,
            @RequestParam(required = false) LocalDateTime endTime,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        return R.ok(operationLogService.getOperationLogs(
            username, module, type, startTime, endTime, pageNum, pageSize));
    }
    
    /**
     * 清理日志
     */
    @DeleteMapping("/clean")
    @PreAuthorize("hasAuthority('system:log:delete')")
    public R<Void> cleanLogs(@RequestParam Integer days) {
        operationLogService.cleanLogs(days);
        return R.ok();
    }
    
    /**
     * 导出日志
     */
    @GetMapping("/export")
    @PreAuthorize("hasAuthority('system:log:export')")
    public void exportLogs(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String module,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) LocalDateTime startTime,
            @RequestParam(required = false) LocalDateTime endTime,
            HttpServletResponse response) throws IOException {
        byte[] data = operationLogService.exportLogs(username, module, type, startTime, endTime);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=operation_logs.xlsx");
        response.getOutputStream().write(data);
    }
} 